<template>
  <div>
    <!--1.编辑面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>


    <!--3.定义卡片视图-->
    <el-card class="box-card">

      <!--定义一个布局-->
      <el-row :gutter="20">
        <!--定义输入框-->
          <el-col :span="9">
        <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" clearable @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
        </el-input>
          </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!--用户信息展示的表格-->
      <el-container>
        <el-table :data="userList" stripe style="width: 100%">
          <!-- 定义表格的序号 -->
          <el-table-column type="id" label="序号"></el-table-column>
          <el-table-column prop="username" label="用户名" ></el-table-column>
          <el-table-column prop="email" label="邮箱" ></el-table-column>
          <el-table-column prop="phone" label="电话" ></el-table-column>
          <el-table-column prop="status" label="状态" >
            <!---作用域插槽-->
            <template slot-scope="scope">
              <!---通过scope封装的对象，获取行级元素，row属性-->
              <!--定义一个开关，关联status-->
              <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949" @change="updateStatus(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" >
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" :v-model="scope.row" size="small" @click="updateUserDialogVisible = true"></el-button>
              <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteUser(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-footer>
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryInfo.pageNum"
              :page-sizes="[1, 5, 20, 40]"
              :page-size="queryInfo.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
        </el-pagination>
        </el-footer>
      </el-container>

    </el-card>

    <!--
        :visible.sync  控制对话框是否展现
      -->
      <el-dialog title="用户新增" :visible.sync="addUserDialogVisible" width="65%"
          @close="closeAddUserDialog">
        <el-form :model="addUserForm" :rules="rules" ref="addUserRuleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="密码确认" prop="password2">
            <el-input v-model="addUserForm.password2" type="password"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="addUserForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>


      <el-dialog title="用户修改" :visible.sync="updateUserDialogVisible" width="65%"
          @close="closeAddUserDialog">
        <el-form :data="addUserForm" :model="addUserForm" :rules="rules" ref="addUserRuleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username" disabled ></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="addUserForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updateUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateUser">确 定</el-button>
        </span>
      </el-dialog>


  </div>
</template>

<script>
export default {
  // 页面加载完成后调用该函数
  mounted() {
    this.getUserList()
  },
  data() {
    //自定义校验规则 rule:当前规则对象一般不用  value: 当前校验的数据  callback:回调函数
      //校验邮箱规则
      const checkEmail = (rule, value, callback) => {
        //定义邮箱的正则表达式  JS中用/来表示正则表达式的开始和结束
        const emailRege = /^[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$/
        if (emailRege.test(value)) {
          //表示邮箱合法 正确返回  通过返回true   失败返回false
          return callback() //自定义规则执行成功,之后后续操作
        }
        callback(new Error('请填写正确的邮箱地址'))
      }

      //校验手机号的邮箱规则
      const checkPhone = (rule, value, callback) => {

        //定义校验手机号的正则语法
        const phoneRege = /^1[3456789][0-9]{9}$/
        if (phoneRege.test(value)) {

          return callback()
        }
        callback(new Error('请填写正确的手机号'))

      }

      //密码确认  判断与password是否相同
      const checkPassword = (rule, value, callback) => {

        if(value !== this.addUserForm.password){
           return callback(new Error('2次密码填写不一致'))
        }
        //如果相同,则调用回调函数
        callback()
      }


    return {
      userList: [],
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 20
      },
      total: 0,
      addUserDialogVisible: false,
      updateUserDialogVisible: false,
        //设定新增用户的对象
      addUserForm: {
        username: '',
        password: '',
        password2:  '',
        phone:  '',
        email:  ''
      },
      updateUserForm: {
        username: '',
        phone: '',
        email: ''
      },
      rules: {
        username: [
                  { required: true, message: '请输入用户名', trigger: 'blur' },
                  { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
                ],
        password: [
                  { required: true, message: '请输入密码', trigger: 'blur' },
                  { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
                ],
        password2: [
                  { required: true, message: '请输入密码', trigger: 'blur' },
                  { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
                  { validator: checkPassword, trigger: 'blur' }
                ],
        phone: [
                  { required: true, message: '请输入电话', trigger: 'blur' },
                  { min: 11, max: 11, message: '长度必须11个字符', trigger: 'blur' },
                  { validator: checkPhone, trigger: 'blur' }
                ],
        email: [
                  { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                  { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
                  { validator: checkEmail, trigger: 'blur' }
                ]
      }
    }
  },
  methods: {
    async getUserList(){
      const {data: result} =  await this.$http.get("/user/list")
      if(result.code !== 20000) return this.$message.error("获取列表失败")
      this.userList = result.data
      this.queryInfo = result.data
      this.total = result.data.total
    },
    // 更改页面的size
    handleSizeChange(pagesize) {
        this.queryInfo.pageSize = pagesize
        this.getUserList()
    },
    // 更改页数
    handleCurrentChange(pagenum){
      this.queryInfo.pageNum = pagenum
      this.getUserList()
    },
    // 根据用户的id修改用户的状态
    async updateStatus(user){
      const {data: result} =  await this.$http.get(`/user/updateUserStatus/${user.id}/${user.status}`)
      console.log("修改")
    },
    closeAddUserDialog(){
        //当对话框关闭时,应该重置表单
        this.$refs.addUserRuleForm.resetFields()
      },
    // 添加用户
    async addUser(){
        const {data: result} =  await this.$http.post('/user/addUser',this.addUserForm)
        if(result.code !== 200) return this.$message.error(result.msg)

        this.addUserDialogVisible = false
        this.$message.info("添加用户成功")
        this.getUserList()
    },
    // 删除用户
    async deleteUser(user){
        //定义消息确认框 promise对象 如果从中获取用户的选项 不方便
        const result = await this.$confirm('此操作将永久删除'+user.username+', 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }).catch(error => error)

        //确定: confirm   取消 cancel
        if(result !== 'confirm') return this.$message.info("用户取消操作")

        //发起ajax请求实现数据的删除...
        const {data: resultDB} = await this.$http.get('/user/delete?id='+user.id)
        if(resultDB.code !== 200) return this.$message.error("用户删除失败!")
        this.$message.success("用户删除成功!")
        //重新加载用户列表
        this.getUserList()
    },
    async updateUser(){
      const {data: result} =  await this.$http.post('/user/update',this.updateUserForm)
      console.log(result.data)
    }
  }
}
</script>

<!--
  当前样式是否支持less语法 样式的一种语言
  scoped 让样式只对当前组件有效 防止样式击穿
 -->
<style lang="less" scoped>

</style>
